package com.yyhu.auto

import groovy.json.JsonBuilder
import org.apache.http.util.TextUtils
import org.json.JSONArray
import org.json.JSONObject
import org.stringtemplate.v4.ST

import javax.crypto.Cipher
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.PrivateKey
import java.security.PublicKey

class UploadTmp {
    TmpInfoBean infoBean = null

    UploadTmp(TmpInfoBean infoBean) {
        this.infoBean = infoBean
    }

    JSONArray getAppDependency() {
        if (!TextUtils.isBlank(infoBean.depAppVersion) && !TextUtils.isBlank(infoBean.depAppName)) {
            JSONArray jsonArray = new JSONArray()
            JSONObject obj = new JSONObject()
            obj.put("appName", infoBean.depAppName)
            obj.put("appVersion", infoBean.depAppVersion)
            jsonArray.put(obj)
            return jsonArray
        }

        return null
    }

    JSONArray getMachineInfoList() {
        JSONArray jsonArray = new JSONArray()
        ArrayList androidVersionList = new ArrayList<String>()
        androidVersionList.add("13")
        if (infoBean.deviceList.size() > 0) {
            for (i in 0..<infoBean.deviceList.size()) {
                String itemDevice = infoBean.deviceList.get(i)
                JSONObject obj = new JSONObject()
                obj.put("machineName", itemDevice)
                obj.put("androidVersionList", androidVersionList)
                jsonArray.put(obj)
            }
        }
        return jsonArray
    }

    String sendTmp(String token, Integer userId) {
        def client = new okhttp3.OkHttpClient()
        def version = infoBean.apkVersion
        def tmpNote = infoBean.gitCommitMsg
        //自测用例
        def selfTestPlanId = infoBean.selfTestPlanId
        def ftpPath = infoBean.apkFtpPath
        def apkName = ftpPath.split("/").last()
        def appName = infoBean.appName
        if ("SunmiNewCit".equalsIgnoreCase(infoBean.appName)) {
            appName = "SunmiCit"
        }
        def machineInfoList = getMachineInfoList()
        println("machineInfoList:$machineInfoList.${machineInfoList}")

        JSONObject jsonObject = new JSONObject()
        jsonObject.put("userId", userId)
        jsonObject.put("machineType", "1")
        jsonObject.put("apkName", apkName)
        jsonObject.put("appName", appName)
        jsonObject.put("projectId", infoBean.projectId)
        jsonObject.put("version", version)
        jsonObject.put("apkPath", "$ftpPath")
        jsonObject.put("developmentManagerId", userId)
        jsonObject.put("relatedMemberId", null)
        jsonObject.put("branch", "NA")
        jsonObject.put("appDependency", getAppDependency())
        jsonObject.put("romDependency", null)
        jsonObject.put("releaseNote", "$tmpNote")
        jsonObject.put("selfTestPlanId", selfTestPlanId)
        jsonObject.put("testSuggestion", null)
        jsonObject.put("machineInfoList", machineInfoList)
        jsonObject.put("machineType", 4)
        if (infoBean.relatedMemberId != null && infoBean.relatedMemberId.size() > 0) {
            jsonObject.put("relatedMemberId", infoBean.relatedMemberId)
        }
        // 动态构建参数
        def jsonStr = jsonObject.toString()
        logI("TMP 提测参数:$jsonStr")
        def requestBody = okhttp3.RequestBody.create(jsonStr,
                okhttp3.MediaType.parse("application/json"))
        def request = new okhttp3.Request.Builder()
                .url("https://tmp-defender.sunmi.com/tmpdefender/createTestSubmissionForm")
                .header("token", token)
                .post(requestBody)
                .build()
        String sunmiResult = ""
        try {
            def response = client.newCall(request).execute()
            def responseStr = response.body().string()
            sunmiResult = responseStr
            logI("TMP 提测结果:$responseStr")
        } catch (Exception e) {
            println "TMP 提测结果: Exception ${e.message}"
        }
        return sunmiResult
    }

    private void logI(String msg) {
//        println(msg)
    }

    String loginTmp() {
        println("loginTmp:${infoBean.toString()}")
        if (infoBean == null) {
            return "TMP信息不能为空"
        }
        def params = [
                "account" : infoBean.tmpAccount,
                "password": infoBean.tmpPassword
        ]
        def jsonStr = new JsonBuilder(params).toString()
        def requestBody = okhttp3.RequestBody.create(jsonStr,
                okhttp3.MediaType.parse("application/json"))
        def request = new okhttp3.Request.Builder()
                .url("https://tmp-defender.sunmi.com/tmpdefender/login")
                .post(requestBody)
                .build()
        try {
            def client = new okhttp3.OkHttpClient()
            def response = client.newCall(request).execute()
            def responseStr = response.body().string()
            println "TMP 登陆结果,code: ${response.code()}"
            def jsonObj = new groovy.json.JsonSlurper().parseText(responseStr)
            if (jsonObj.code == 1) {
                String uploadResult = ""
                println "开始提交TMP 提测信息 ${jsonObj.data != null}"
                if (jsonObj.data != null) {
                    def token = jsonObj.data.token
                    def userId = jsonObj.data.userId
                    uploadResult = sendTmp(token, userId)
                }
                return uploadResult
            } else {
                return responseStr
            }
        } catch (Exception e) {
            println "Failed to send build report: ${e.message}"
            return e.toString()
        }
    }

    PrivateKey getPrivateKey(String key) {
        def decoded = Base64.decode(key.toByteArray(), Base64.DEFAULT)
        def keySpec = PKCS8EncodedKeySpec(decoded)
        def keyFactory = KeyFactory.getInstance(RSA)
        return keyFactory.generatePrivate(keySpec)
    }

    // 生成RSA密钥对
    def generateKeyPair() {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA")
        keyPairGenerator.initialize(2048)
        return keyPairGenerator.generateKeyPair()
    }

    // RSA加密
    def rsaEncrypt(String data, PublicKey publicKey) {
        Cipher cipher = Cipher.getInstance("RSA")
        cipher.init(Cipher.ENCRYPT_MODE, publicKey)
        byte[] encryptedBytes = cipher.doFinal(data.bytes)
        return encryptedBytes.encodeBase64().toString()
    }

}
